from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage
import json

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
from django.utils.deprecation import MiddlewareMixin
# from rest_framework_jwt.utils import jwt_decode_handler
import jwt,time
from jwt.exceptions import ExpiredSignatureError,DecodeError
from django.http import JsonResponse
from django.conf import settings

from myapp.models import OperationLogModel

import re,datetime,json

class MyRBAC(MiddlewareMixin):
    def process_request(self, request):
        try:
            # x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
            # if x_forwarded_for:
            #     ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
            # else:
            #     ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
            #
            # address = self.cz.get_addr_by_ip(ip)
            # facility = request.headers.get("User-Agent")
            # print(f"访问ip {ip} 时间 {datetime.datetime.now()}")
            # print(f"地址 {address} 设备 {facility}")
            #
            path = request.path_info
            method = request.method.lower()  # GET = get
            print(method, path)

            if re.findall("login|img_code|amend_pwd", path, re.I):
                return None

            token = request.headers.get("Authorization")
            try:
                payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms=['HS256'])
                request.session["user"] = payload
            except ExpiredSignatureError:
                return JsonResponse({"code": 401, "message": "token过期"})
            except DecodeError:
                return JsonResponse({"code": 402, "message": "请重新登录"})

            staff_id = payload.get("user_id")
            print(f"访问用户{staff_id}")

            # 操作日志
            # if method != "get":
            #     for i in self.permission:
            #         per_method = i.path.split()[0]
            #         per_path = i.path.split()[1]
            #         if re.findall(per_path, path, re.I) and method == per_method:
            #             OperationLogModel.objects.create(user=staff_id, router=f"{method} {path}", operation=i.name,
            #                                             times=datetime.datetime.now())
        except Exception as e:
            print("请求中间件错误", e)
            return JsonResponse({"code": 500, "message": "服务器错误！"}, status=200)